import { getListApi, deleteApi, cancelApi } from "@/api/exportCenter/exportQueue";
import { Modal, message } from "ant-design-vue";
import { computed, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";

export default function OperationHook(state: Base.GeneraDataType) {
  const { searchForm, loading, tableData, tableRef, downloadFileByUrl } = state;
  const selectRows = computed<Array<ExportCenterManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const getData = async () => {
    const params = {
      ...getParams()
    };
    loading.value = true;
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    getData();
  };

  const getParams = () => {
    const { exportName, status, pageNum, pageSize, total } = searchForm;
    const params: any = {
      exportName,
      status,
      pageNum,
      pageSize,
      total
    };
    return params;
  };
  //导出
  const downFileHandle = (row: ExportCenterManagement.ListRows) => {
    downloadFileByUrl(row.url, `${row.exportName}.xlsx`);
  };

  // 删除
  const deleteHandle = (row: ExportCenterManagement.ListRows) => {
    const params: any = {
      idList: [row.id]
    };
    Modal.confirm({
      title: "是否删除任务?",
      icon: createVNode(ExclamationCircleOutlined),
      content: "",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        deleteApi(params).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            getData();
          }
        });
      }
    });
  };

  //批量删除

  const barchDeleteHandle = () => {
    if (!selectRows.value.length) return message.error("请选择数据!");
    const params: any = {
      idList: selectRows.value.map((t: any) => t.id)
    };
    Modal.confirm({
      title: "是否删除任务?",
      icon: createVNode(ExclamationCircleOutlined),
      content: "",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        deleteApi(params).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            getData();
          }
        });
      }
    });
  };
  //取消
  const cancelHandle = (row: ExportCenterManagement.ListRows) => {
    const params = {
      idList: [row.id]
    };
    cancelApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("操作成功!");
        getData();
      }
    });
  };

  return {
    getData,
    searchHandle,
    downFileHandle,
    deleteHandle,
    cancelHandle,
    barchDeleteHandle
  };
}
